# -*- coding: utf-8 -*-
from flask_httpauth import HTTPBasicAuth
from flask import g, jsonify

from ..models import User, Anonymous
from .errors import unauthorized, forbidden
from . import api

auth = HTTPBasicAuth()


@auth.verify_password
def verify_password(email_or_token, password):
    g.current_user = Anonymous()
    if email_or_token == '':
        g.current_user = Anonymous()
        return False
    if password == '':
        g.current_user = User.verify_auth_token(email_or_token)
        g.token_used = True
        return g.current_user is not None
    user = User.query.filter_by(username=email_or_token).first()
    if not user:
        g.current_user = Anonymous()
        return False

    g.current_user = user
    g.token_used = False
    return user.verify_password(password)


@auth.error_handler
def auth_error():
    return unauthorized('Invalid credentials.')


@api.before_request
def before_request():
    try:
        if not g.current_user.is_anonymous and \
                not g.current_user.status:
            return forbidden('Unconfirmed account')
    except:
        pass


@api.route('/token')
@auth.login_required
def get_token():
    if g.current_user.is_anonymous or g.token_used:
        return unauthorized('Invalid credentials.')
    return jsonify({'token': g.current_user.generate_auth_token(
        expiration=3600), 'expiration': 3600})